摘要
昨天(Day 5)我們學會了把拖延紀錄存進 LocalStorage,避免重整網頁後資料消失。
但資料現在「藏在瀏覽器裡」,使用者還看不到。
今天,我們要把這些紀錄讀出來,顯示在網頁上,做成「歷史回顧清單」,並且提供「一鍵清空」的功能。
看到自己過去的紀錄,更有「持續感」。
昨天的核心流程:
「讀 → parse → push → stringify → setItem」
→ 把新資料寫進去。
今天要反過來:
「讀 → parse → render」
→ 把資料讀出來並畫在頁面上。
實作步驟
接下來會沿用 Day 5 的 index.html、script.js,分別用於「網頁呈現」與「記錄 LocalStorage、渲染歷史清單」。
<h2>歷史回顧</h2>
<ul id="historyList"></ul>
<button id="clearBtn">清空紀錄</button>
function renderHistory() {
const el = document.getElementById('historyList');
const records = readRecords().slice().reverse(); // 近的在上
el.innerHTML = records.length
? records.map(r =>
`<li>[${new Date(r.createdAt).toLocaleString()}] ${r.task} — ${r.reason} |「${r.quote}」</li>`
).join("")
: "<li>尚無紀錄</li>";
}
function clearHistory() {
localStorage.removeItem(STORAGE_KEY);
renderHistory();
}
document.getElementById('clearBtn').addEventListener('click', clearHistory);
renderHistory();
先在 Day 5 做的表單填幾筆資料。
重整頁面 → 歷史清單應該出現。
點「清空紀錄」 → 清單變成「尚無紀錄」。